//
//  MainViewController.m
//  memory
//
//  Created by Storm Christoph on 12/23/09.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "MainViewController.h"
#import "MainView.h"

#define kImageHeight		50.0
#define kImageWidth			50.0
#define kTransitionDuration	0.75

#define kTopPlacement		80.0	// y coord for the images

//todo: to be defined by user (properties menue)
int optionsNrOfCards = 16;					// nr of cards to play with
int optionsCardsToCompare = 2;				// how many cards must be compared
int optionsSecondsToRun = 60;
int optionsTypeOfCards = 0;					//0..numbers, 1..symbols, 2..pictures

int cardHeight = 97;				// height of one game card
int cardWidth = 70;					// with of one game card

double sampleRate = 10.0;
double cutoffFrequency = 5.0;
double updateInterval = (1.0 / 60.0);
int currentRoundNr = 0;


NSMutableArray *cardArray = nil;
NSMutableArray *positionArray = nil;
GameController *gameController = nil;
FlipsideViewController *flipSideController = nil; 


@implementation MainViewController

@synthesize containerView, mainView, flipToView, labelRound, timeBar;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}

 - (void)viewDidLoad {
	 [super viewDidLoad];
	 
	 // init accelerator
	 filter = [[[HighpassFilter class] alloc] initWithSampleRate:sampleRate cutoffFrequency:cutoffFrequency from:self];
	 [[UIAccelerometer sharedAccelerometer] setUpdateInterval: updateInterval];
	 [[UIAccelerometer sharedAccelerometer] setDelegate:self];
	 
	 // recreate game controller when user changes settings, e.g. when nr of cards will be changed
	 gameController = [[GameController alloc] initWithParameters:optionsNrOfCards group:optionsCardsToCompare view:(id *)self timer:optionsSecondsToRun];
	 
	 // init option values
	 optionsSecondsToRun = 60;			// how long does one game run
	 
	 // create cards
	 [self createCards];
 }

#pragma mark-
#pragma mark AccelerometerFiler
// UIAccelerometerDelegate method, called when the device accelerates.
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
	// Update the accelerometer graph view
	
	[filter addAcceleration:acceleration];
	//	[unfiltered addX:acceleration.x y:acceleration.y z:acceleration.z];
	//	[filtered addX:filter.x y:filter.y z:filter.z];
}

-(void)createCards
{	
	// delete all existing cards first (for game restart)
	if (cardArray != nil) {
		for (int i=0; i<[cardArray count]; i++)
		{
			[((Card *)[cardArray objectAtIndex:i]) removeFromSuperview];
		}
		[cardArray removeAllObjects];
	}
	
	// create new cards
	[self calcCardSize];
	cardArray = [[NSMutableArray alloc] init];
	Card* card = nil;
	
	int group = 0;
	int groupCounter = optionsCardsToCompare;
	
	[self calculatePositions:optionsNrOfCards];
	
	// randomize positions array -> shake the cards
	NSUInteger firstObject = 0;	
	for (int i = 0; i<[positionArray count]; i++) 
	{
		NSUInteger randomIndex = random() % [positionArray count];
		[positionArray exchangeObjectAtIndex:firstObject withObjectAtIndex:randomIndex];
		firstObject +=1;
		
	}
	
	for (int i = 0; i < optionsNrOfCards; i++) {
		MyPoint *p = [[positionArray objectAtIndex:0] retain];		
		[positionArray removeObjectAtIndex:0];
		
		// 2do: group muss noch gemacht werden, sollte nicht 0 sein
		card = [self createCardWithX:p.x Y:p.y Counter:i Group:group];
		[cardArray addObject:card];
		[p release];
		
		groupCounter--;
		if (groupCounter == 0) {
			group++;
			groupCounter = optionsCardsToCompare;
		}
	}
	
	timeBar.progress = 1.0;
	
}

-(void) updateTimerBar:(CGFloat) progress
{
	NSLog(@"Bar: %f",progress);
	timeBar.progress = progress;
}

-(void) onTimer 
{
	NSLog(@"Game over - time out");
	
	UIAlertView *gameOver = [[UIAlertView alloc] initWithTitle: @"Game over" message: @"You run out of time ..." delegate: self cancelButtonTitle: @"Start new Game" otherButtonTitles: nil];
	[gameOver show];
	[gameOver release];
}

-(void) onGameSolved:(int) seconds round:(int) roundNr
{
	currentRoundNr = roundNr;
	
	NSLog(@"Game solved within time");
	NSString *msg = [NSString stringWithFormat:@"you solved the game within %d seconds",seconds];
	
	UIAlertView *gameSolved = [[UIAlertView alloc] initWithTitle: @"Contratulation!" message: msg delegate: self cancelButtonTitle: @"Start new Game" otherButtonTitles: nil];
	[gameSolved show];
	[gameSolved release];
}

-(void) onShake
{
	NSLog(@"Shaked - start new game?");
	
	[gameController pauseTimer];
	
	UIAlertView *shaked = [[UIAlertView alloc] initWithTitle: @"Phone shaked!" message: @"Start new game?" delegate: self cancelButtonTitle: @"Yes" otherButtonTitles: @"No", nil];
	[shaked show];
	[shaked release];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{
	
	if (buttonIndex == 0)
	{
		NSLog(@"new game clicked");
		[self startNewGame];	

	} else if (buttonIndex == 1) 
	{
		NSLog(@"button index 1 - no clicked");
		
		[gameController resumeTimer];
	}
}

-(void) startNewGame
{
	// deletes old cards and creates new cards for new game
	[self createCards];
	
	//NSLog(@"round %d", currentRoundNr);
	NSString *round = [NSString stringWithFormat:@"round: %d",currentRoundNr];
	
	// actual round to label
	labelRound.text = round;
	
	// Set game controller to default values
	[gameController initParameters:optionsNrOfCards group:optionsCardsToCompare timer:optionsSecondsToRun];
}


//
// calculate the positions of the cards
//
-(void) calculatePositions:(int) nrOfCards
{
	positionArray = [[NSMutableArray alloc] init];
	
	int border = 5;
	int gap = 5;
	
	//	int totalH = self.view.bounds.size.height - (20+15);
	//	int totalW = self.view.bounds.size.width;
	
	
	for (int j=0; j<sqrt(nrOfCards); j++) {
		for (int i=0; i<sqrt(nrOfCards); i++) {
			
			MyPoint *p = [[MyPoint alloc] init];
			
			p.x = border+(cardWidth+gap)*j;
			p.y = border+(cardHeight+gap)*i;
			
			[positionArray addObject:p];
			[p release];
		}
	}
}

- (void)calcCardSize
{
	//	int h = self.view.bounds.size.height;
	//	int w = self.view.bounds.size.width;
	
	//cardHeight = (h - (8*5) / 4);
	//cardWidth = (w -(8*5) / 4);
}

-(Card*)createCardWithX:(int)xPos Y:(int)yPos Counter:(int)counterID Group:(int)groupID
{
	frame = CGRectMake(xPos, yPos, cardWidth, cardHeight);
	
	NSString *pic;
	
	switch (optionsTypeOfCards) {
		case 1:
			pic = [NSString stringWithFormat:@"%d%@",(groupID+1),@"symbol.png"];
			break;
		case 2:
			pic = [NSString stringWithFormat:@"%d%@",(groupID+1),@"picture.png"];
			break;
		default:
			pic = [NSString stringWithFormat:@"%d%@",(groupID+1),@"number.png"];
			break;
	}
	
	Card *dragger = [[Card alloc] initWithFrame:frame 
									 frontImage:[UIImage imageNamed:pic] 
									  backImage:[UIImage imageNamed:@"back.png"]
									 gameCardID:counterID
									gameGroupID:groupID
					 ];
	dragger.delegate = self;
	[dragger setUserInteractionEnabled:YES]; 
	[self.view addSubview:dragger];
	[dragger release];
	
	return dragger;
}

- (void)cardFlipped:(Card *) card
{
	[gameController checkGroupFound];	
}


-(BOOL)cardShouldFlip:(Card *)card
{
	NSLog(@"Controller: card should flip? %i %i", card.cardID, card.groupID);
	
	return [gameController cardShouldFlip:card];
}






/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller {
    
	[self dismissModalViewControllerAnimated:YES];
	
	BOOL newGame = NO;
	
	if(optionsSecondsToRun != flipSideController.optionsSecondsToRun)
	{
		optionsSecondsToRun = flipSideController.optionsSecondsToRun;
		newGame = YES;
	}
	
	if(optionsNrOfCards != flipSideController.optionsNrOfCards)
	{
		optionsNrOfCards = flipSideController.optionsNrOfCards;
		newGame = YES;
	}
	if(optionsCardsToCompare != flipSideController.optionsCardsToCompare)
	{
		optionsCardsToCompare = flipSideController.optionsCardsToCompare;
		newGame = YES;
	}
	if(optionsTypeOfCards != flipSideController.optionsTypeOfCards)
	{
		optionsTypeOfCards = flipSideController.optionsTypeOfCards;
		newGame = YES;
	}
	
	if (newGame) 
	{
		[self startNewGame];
	}
	else 
	{
		[gameController resumeTimer];
	}

	
	
}


- (IBAction)showInfo {    
	
	[gameController pauseTimer];
	
	flipSideController = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
	flipSideController.delegate = self;
	
	flipSideController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:flipSideController animated:YES];
	
	//
}



/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.flipToView = nil;
	self.mainView = nil;
}


- (void)dealloc {
	[positionArray release];
    [cardArray release];
	
	[flipSideController release];
	
    [super dealloc];
}


@end
